package com.example.interceptor;

import com.example.utils.JwtUtils;
import com.example.utils.ThreadLocalUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 令牌验证
        String token = request.getHeader("Authorization");
        System.out.println(token);
//        String url = request.getRequestURI();
//        System.out.println("请求地址："+url + "；token：" + token);
        // 解析token
        try {
            Map<String, Object> claims = JwtUtils.verifyToken(token);
            // 存储业务数据
            ThreadLocalUtils.set(claims);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 清空ThreadLocal数据，防止内存泄漏
        ThreadLocalUtils.remove();
    }
}
